﻿package org.kolonitsky.alexey.banner {

    import com.carlcalderon.arthropod.Debug;
    
    import flash.display.ActionScriptVersion;
    import flash.display.MovieClip;
    import flash.events.ContextMenuEvent;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.net.URLRequest;
    import flash.net.navigateToURL;
	import flash.ui.ContextMenu;
    import flash.ui.ContextMenuItem;
    

    /**
     * Base class for all banners. Main purpose for <code>TUTBanner</code> class --- 
     * create bannerClick button, detect additional information about banner from file 
     * name, and get target link from flash vars. In addion hide default Flash Player 
     * menu.
     * @date 11.05.2009
     * @update 3.11.2009
     * @author Alexey Kolonitsky
     * @version 0.0.3
     */
    dynamic public class TUTBanner extends MovieClip 
    {
        /**
         * Default banner url. Used if not specified bannerLink parameter by any other ways
         */
        private static const DEFAULT_URL:String = "http://www.tut.by/";
        
        /**
         * Link to details information about advertisment on portal
         */ 
        private static const ADV_MENU_ITEM_URL:String = "http://www.tutby.com/service/advert/main/";
        
        /**
         * Planed banner width.
         * Used when resize banner for positioned react area
         */
        public var bannerWidth:Number;
        
        /**
         * Planed banner height
         */
        public var bannerHeight:Number;

        /** 
         * Banner button. If banner batton not defined on timeline
         * them drawed, and placed on child's chain top.
         */
        public var bannerButton:MovieClip;

        /**
         * Banner Management System Identifier 
         */
        public var bannerId:uint = 0;

        /**
         * Banner target url.
         */
        public var bannerLink:String =  DEFAULT_URL;

        /**
         * Show debug information
         */
        public var showDebugInformation:Boolean = false;


        /**
         * Constructor 
         */
        public function TUTBanner () 
        {
            super()
            log("CreateBanner. v0.0.3");
            
            parsFileName()
            getExternalParameters()
            
            addEventListener(Event.ENTER_FRAME, addToStageHandler)

            // init stage if this flash not load into other swf
            try 
            {
                prepareStage()
            } 
            catch (err:SecurityError)
            {
                Debug.error("ERR: " + err.message)
            } 
            catch (err:Error) 
            {
                Debug.error("EFF: " + err.message)
            }
        }


        /** 
         * Start init banner 
         */
        protected function addToStageHandler(event:Event): void 
        {
            removeEventListener(Event.ENTER_FRAME, addToStageHandler)
            if (bannerLink == DEFAULT_URL && bannerId != 0) 
                bannerLink = "http://preved.tut.by/?clickid=" + bannerId;
            resizeHandler();
        }


        /**
         * Default stage properties
         */
        protected function prepareStage():void
        {
            stage.align = "T";
            stage.scaleMode = "showAll";
            stage.addEventListener(Event.RESIZE, resizeHandler);
        }


        /**
         * 
         */
        private function updateBannerButton():void
        {
			// Button created or defined on timeline
            if (bannerButton /*&& stage.scaleMode != "noScale"*/)
            {
                log("bannerButton exists")
//                bannerButton.width = bannerWidth;
//                bannerButton.height = bannerHeight;
                bannerButton.useHandCursor = true;
                bannerButton.buttonMode = true;

            }
			// Button not exists
            else
            {
                log("TUTBanner.updateBannerButton = " + stage.align)
                var xPos: Number = stage.align.indexOf("L") < 0 ? bannerWidth / 2 : 0; 
                var yPos: Number = stage.align.indexOf("T") < 0 ? bannerHeight / 2 : 0;
                if (bannerButton) 
                {
                    removeChild(bannerButton)
                    bannerButton = null
                }
                bannerButton = new MovieClip();
                bannerButton.useHandCursor = true;
                bannerButton.buttonMode = true;
				//DBG: Show bannerButton for debug mode
				log(bannerWidth + "x" + bannerHeight)
				if (isNaN(bannerWidth) || isNaN(bannerHeight))
				{
					trace ("WAR: need specify bannerWidth and bannerHeight parameters," +
						" now used standard size 100x100.");
					bannerWidth = bannerWidth ? bannerWidth : 100;
					bannerHeight = bannerHeight ? bannerHeight : 100;
				}
					
                bannerButton.graphics.beginFill(0x00FF00, (showDebugInformation ? 0.3 : 0.0));
                bannerButton.graphics.drawRect(-xPos, -yPos, bannerWidth, bannerHeight);
                bannerButton.graphics.endFill();
				//DBG: Show centered point
                if (showDebugInformation) 
                {
					bannerButton.graphics.beginFill(0xFF0000, 1);
					bannerButton.graphics.drawCircle(0, 0, 1);
					bannerButton.graphics.endFill();
				}
				bannerButton.x = xPos;
				bannerButton.y = yPos;
                addChild(bannerButton);

            }
            if (!bannerButton.hasEventListener(MouseEvent.MOUSE_UP))
                bannerButton.addEventListener(MouseEvent.MOUSE_UP, onBannerClick);
            createContextMenu();
        }


        /**
         * Fill context menu
         */
        private function createContextMenu():void
        {
            var advContext:ContextMenuItem = new ContextMenuItem("Реклама ТУТ!");
            advContext.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, advMenuItemSelectHandler)
            bannerButton.contextMenu = new ContextMenu()
			bannerButton.contextMenu.customItems = [advContext] 
			bannerButton.contextMenu.hideBuiltInItems()
        }
        
        
        private function advMenuItemSelectHandler(event:ContextMenuEvent):void
        {
            log("advMenuItemSelectHandler, url = " + ADV_MENU_ITEM_URL)
            navigateToURL(new URLRequest(ADV_MENU_ITEM_URL), "_blank");
        }


        /** Goto url if it defined in banner **/
        private function onBannerClick (event:MouseEvent): void 
        {
            log("onBannerClick() gotoURL: " + bannerLink);
            navigateToURL(new URLRequest(bannerLink), "_blank");
        }


        /** 
         * Get external parameters form flashvars if it defined or
         * from timeline.
         */
        private function getExternalParameters (): void 
        {
            var param: Object = root.loaderInfo.parameters;
            if (param.link1) bannerLink = param.link1;			// old tut.by banner system
			if (param.clickTAG) bannerLink = param.clickTAG;	// openx banner system
            if (param.bannerId) bannerId = param.bannerId;
            if (param.debug) showDebugInformation = true;
        }


        /**
         * Pars file name for detect information about typical banner properties
         * Detected file name like ####_category###x###-####
         */
        private function parsFileName (): void
        {
            var fileName:String = loaderInfo.url
            var namePattern:RegExp = /[\d\w%]*\.swf/i;
            var idPattern:RegExp = /\d{1,4}/i;
            var sizePattern:RegExp = /(\d{1,4})x(\d{1,4})/i;
            
            // Select banner filename
            var swfName:String = namePattern.exec(fileName);
            if (swfName == null)
                return;
            
			log("Banner file name = " + fileName);
            
            var arId:String = idPattern.exec(swfName);
            if (arId == "") 
				return;
            
            bannerId = uint(arId);
            var arSize:Array = swfName.match(sizePattern);
            
            if (arSize)
            {
                log("\tbannerSize = " + arSize);
                bannerWidth = arSize[1];
                bannerHeight = arSize[2];
                var ind: int = String(arSize[0]).indexOf(arId);
                if (ind >= 0) bannerId = 0;
				else log("\tbannerId = " + bannerId);
            }
        }


        /** Resize banner react area when resize banner **/
        protected function resizeHandler (event:Event=null): void {
			log("TUTBanner.resizeHandler()")
            try 
            {
				if (stage.scaleMode == "noScale") 
				{
					bannerWidth = stage.stageWidth;
					bannerHeight = stage.stageHeight;
				}
            } 
            catch (err:Error) 
            {
                log("ERR: " + err.message);
            }
            updateBannerButton();
        }
		
		
		protected function log (str:String):void
		{
			trace("INF: "+ str)
		}
    }

}